﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PersonalAlbum.Data.Objects;

namespace PersonalAlbum.Data.Entities
{
    public class EntranceRepository : IRepository<Entrance>
    {

        private string _connectionString;
        public EntranceRepository(string connectionString)
        {
            this._connectionString = connectionString;
        }

        #region IDataFactory<Entrance> Members

        public List<Entrance> GetItems()
        {
            using (var ImagesDB = new ImagesDal.SqlEntitiesProvider(this._connectionString))
            {
                return ImagesDB.Entrance.Select(e =>
                    new Entrance()
                    {
                        Id = e.Id,
                        IP = e.IP,
                        Page = e.Page,
                        SessionId = e.SessionId,
                        Timestamp = e.Timestamp,
                        Details = e.Details
                    }).ToList();
            }
        }

        public void AddItem(Entrance item)
        {
            using (var ImagesDB = new ImagesDal.SqlEntitiesProvider(this._connectionString))
            {
                ImagesDal.Entrance e = new ImagesDal.Entrance()
                {
                    Timestamp = item.Timestamp,
                    SessionId = item.SessionId,
                    IP = item.IP,
                    Page = item.Page,
                    Details = item.Details
                };
                ImagesDB.AddToEntrance(e);
                ImagesDB.SaveChanges();
                item.Id = e.Id;
            }
        }

        public void DeleteItem(Entrance item)
        {
            using (var ImagesDB = new ImagesDal.SqlEntitiesProvider(this._connectionString))
            {
                var old = ImagesDB.Entrance.FirstOrDefault(s => s.Id == item.Id);
                if (old != null)
                {
                    ImagesDB.DeleteObject(old);
                    ImagesDB.SaveChanges();
                }
            }
        }

        public void UpdateItem(Entrance item)
        {
            throw new NotImplementedException();
        }


        public Entrance GetItemById(int id)
        {
            using (var ImagesDB = new ImagesDal.SqlEntitiesProvider(this._connectionString))
            {
                return ImagesDB.Entrance.Where(e => e.Id == id).Select(e =>
                    new Entrance()
                    {
                        Id = e.Id,
                        IP = e.IP,
                        Page = e.Page,
                        SessionId = e.SessionId,
                        Timestamp = e.Timestamp,
                        Details = e.Details
                    }).SingleOrDefault();
            }
        }

        #endregion
    }
}
